package com.yami.shop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.HotTopicDTO;
import com.yami.shop.bean.model.HotTopics;
import com.yami.shop.bean.model.TopicParticipation;
import com.yami.shop.bean.vo.TopicDetailVO;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.HotTopicMapper;
import com.yami.shop.dao.PostsMapper;
import com.yami.shop.dao.TopicParticipationMapper;
import com.yami.shop.service.HotTopicService;
import com.yami.shop.service.TopicParticipationService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用于存储社区中的热门话题 服务实现类
 * </p>
 *
 * @author EXiaoKe
 * @since 2025-04-14
 */
@Service
public class HotTopicServiceImpl extends ServiceImpl<HotTopicMapper, HotTopics> implements HotTopicService {

    @Resource
    private HotTopicMapper hotTopicMapper;
    @Autowired
    private PostsMapper postMapper;
    @Resource
    private  TopicParticipationService participationService;

    @Resource
    private TopicParticipationMapper participationMapper;


    /**
     * 分页获取所有热门话题信息
     *
     * @return 包含分页结果数据的Page对象，其中HotTopicDTO为热门话题数据传输对象，
     * 包含话题基本信息、参与人数、更新时间等核心字段
     */
    @Override
    public List<HotTopics> getAllTopic() {
        //返回话题列表
        List<HotTopics> hotTopics = hotTopicMapper.selectList(null);
        return hotTopics;
    }

    /**
 * 根据话题ID获取话题详情信息
 *
 * @param topicId 要查询的热门话题ID，不可为空
 * @return TopicDetailVO 包含话题基础信息及关联动态数量的视图对象
 */
@Override
public TopicDetailVO getTopicDetail(Long topicId) {
    HotTopics topic = getById(topicId);
    TopicDetailVO vo = new TopicDetailVO();
    BeanUtils.copyProperties(topic, vo);
    // 计算并设置当前话题关联的动态总数
    vo.setPostCount(participationService.countParticipations(topicId));
    return vo;
}
/**
 * 分页查询话题列表及其关联的动态内容
 *
 * @param page  分页参数对象，包含当前页码和分页大小
 * @param topic 查询条件对象，支持按标题模糊查询
 * @return Page<HotTopicDTO> 包含分页信息及话题数据的分页对象，每个话题包含关联的动态列表
 */
        @Override
        public Page<HotTopicDTO> getTopicWithPosts(PageParam<HotTopics> page, HotTopics  topic) {
            // 新增postId处理逻辑
            List<Long> topicIds = Collections.emptyList();
            if (topic != null && topic.getPostId() != null) {
                topicIds = participationService.findTopicIdsByPostId(topic.getPostId());
                if (CollectionUtils.isEmpty(topicIds)) {
                    return new Page<>(page.getCurrent(), page.getSize(), 0);
                }
            }

            // 构建分页参数
            int offset = Math.toIntExact((page.getCurrent() - 1) * page.getSize());

            // 执行改造后的分页查询
            List<HotTopics> hotTopicList = hotTopicMapper.selectTopicsWithParticipation(
                    buildQueryParams(topic, topicIds), // 新增参数处理
                    (int) page.getSize(),
                    offset
            );

            // DTO转换逻辑
            List<HotTopicDTO> dtos = hotTopicList.stream().map(hotTopic -> {
                HotTopicDTO dto = new HotTopicDTO();
                BeanUtils.copyProperties(hotTopic, dto);
                dto.setPosts(postMapper.findPostsByTopicId(hotTopic.getTopicId()));
                return dto;
            }).collect(Collectors.toList());

            // 构建分页结果
            Page<HotTopicDTO> resultPage = new Page<>(page.getCurrent(), page.getSize());
            resultPage.setRecords(dtos);
            resultPage.setTotal(countEnhanced(topic, topicIds));
            return resultPage;
        }

        // 新增查询参数构建方法
        private String buildQueryParams(HotTopics topic, List<Long> topicIds) {
            StringBuilder params = new StringBuilder();
            if (StrUtil.isNotBlank(topic.getTitle())) {
                params.append("title=").append(topic.getTitle());
            }
            if (!CollectionUtils.isEmpty(topicIds)) {
                params.append("&topicIds=").append(StringUtils.join(topicIds, ","));
            }
            return params.toString();
        }

        // 增强版总数统计
        private long countEnhanced(HotTopics topic, List<Long> topicIds) {
            LambdaQueryWrapper<HotTopics> wrapper = new LambdaQueryWrapper<>();
            if (StrUtil.isNotBlank(topic.getTitle())) {
                wrapper.like(HotTopics::getTitle, topic.getTitle());
            }
            if (!CollectionUtils.isEmpty(topicIds)) {
                wrapper.in(HotTopics::getTopicId, topicIds);
            }
            return hotTopicMapper.selectCount(wrapper);
        }




    /**
     * 统计符合条件的话题总数
     *
     * @param topic 查询条件对象，仅使用标题作为过滤条件
     * @return 符合过滤条件的总记录数
     */
    private long count(HotTopics topic) {
        LambdaQueryWrapper<HotTopics> wrapper = new LambdaQueryWrapper<>();
        // 当标题存在时添加模糊查询条件
        if (StrUtil.isNotBlank(topic.getTitle())) {
            wrapper.like(HotTopics::getTitle, topic.getTitle());
        }
        return hotTopicMapper.selectCount(wrapper);
    }
}
